package com.warom.sdg.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.PlcDeviceEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 原生SQLite实现的PlcDeviceDao
 */
public class PlcDeviceDao_Impl implements PlcDeviceDao {
    private static final String TAG = "PlcDeviceDao_Impl";
    
    private final SdgDatabase database;
    
    public PlcDeviceDao_Impl(SdgDatabase database) {
        this.database = database;
    }
    
    @Override
    public long insert(PlcDeviceEntity device) {
        SQLiteDatabase db = database.getWritableDatabase();
        long id = -1;
        
        try {
            ContentValues values = new ContentValues();
            values.put(SdgDatabase.COLUMN_DEVICE_NAME, device.getDeviceName());
            values.put(SdgDatabase.COLUMN_DEVICE_IP, device.getDeviceIp());
            values.put(SdgDatabase.COLUMN_DEVICE_PORT, device.getDevicePort());
            values.put(SdgDatabase.COLUMN_UNIT_ID, device.getUnitId());
            values.put(SdgDatabase.COLUMN_PROTOCOL, device.getProtocol());
            values.put(SdgDatabase.COLUMN_IS_ACTIVE, device.isActive() ? 1 : 0);
            values.put(SdgDatabase.COLUMN_DESCRIPTION, device.getDescription());
            values.put(SdgDatabase.COLUMN_LAST_CONNECT_TIME, device.getLastConnectTime());
            values.put(SdgDatabase.COLUMN_DEVICE_TYPE_ID, device.getDeviceTypeId());
            
            id = db.insert(SdgDatabase.TABLE_PLC_DEVICES, null, values);
            Log.d(TAG, "已插入PLC设备记录，ID: " + id);
        } catch (Exception e) {
            Log.e(TAG, "插入PLC设备失败: " + e.getMessage(), e);
        }
        
        return id;
    }
    
    @Override
    public void update(PlcDeviceEntity device) {
        SQLiteDatabase db = database.getWritableDatabase();
        
        try {
            ContentValues values = new ContentValues();
            values.put(SdgDatabase.COLUMN_DEVICE_NAME, device.getDeviceName());
            values.put(SdgDatabase.COLUMN_DEVICE_IP, device.getDeviceIp());
            values.put(SdgDatabase.COLUMN_DEVICE_PORT, device.getDevicePort());
            values.put(SdgDatabase.COLUMN_UNIT_ID, device.getUnitId());
            values.put(SdgDatabase.COLUMN_PROTOCOL, device.getProtocol());
            values.put(SdgDatabase.COLUMN_IS_ACTIVE, device.isActive() ? 1 : 0);
            values.put(SdgDatabase.COLUMN_DESCRIPTION, device.getDescription());
            values.put(SdgDatabase.COLUMN_LAST_CONNECT_TIME, device.getLastConnectTime());
            values.put(SdgDatabase.COLUMN_DEVICE_TYPE_ID, device.getDeviceTypeId());
            
            int rows = db.update(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    values,
                    SdgDatabase.COLUMN_ID + " = ?",
                    new String[] { String.valueOf(device.getDeviceId()) });
            
            Log.d(TAG, "已更新PLC设备记录，行数: " + rows);
        } catch (Exception e) {
            Log.e(TAG, "更新PLC设备失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public void delete(PlcDeviceEntity device) {
        SQLiteDatabase db = database.getWritableDatabase();
        
        try {
            int rows = db.delete(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    SdgDatabase.COLUMN_ID + " = ?",
                    new String[] { String.valueOf(device.getDeviceId()) });
            
            Log.d(TAG, "已删除PLC设备记录，行数: " + rows);
        } catch (Exception e) {
            Log.e(TAG, "删除PLC设备失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<PlcDeviceEntity> getAllDevices() {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDeviceEntity> deviceList = new ArrayList<>();
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    null,
                    null,
                    null,
                    null,
                    SdgDatabase.COLUMN_DEVICE_NAME + " ASC");
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    deviceList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取全部设备失败: " + e.getMessage(), e);
        }
        
        return deviceList;
    }
    
    @Override
    public PlcDeviceEntity getDeviceById(int deviceId) {
        SQLiteDatabase db = database.getReadableDatabase();
        PlcDeviceEntity entity = null;
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    SdgDatabase.COLUMN_ID + " = ?",
                    new String[] { String.valueOf(deviceId) },
                    null,
                    null,
                    null);
            
            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按ID获取设备失败: " + e.getMessage(), e);
        }
        
        return entity;
    }
    
    @Override
    public PlcDeviceEntity getDeviceByIpAndPort(String deviceIp, int devicePort) {
        SQLiteDatabase db = database.getReadableDatabase();
        PlcDeviceEntity entity = null;
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    SdgDatabase.COLUMN_DEVICE_IP + " = ? AND " + SdgDatabase.COLUMN_DEVICE_PORT + " = ?",
                    new String[] { deviceIp, String.valueOf(devicePort) },
                    null,
                    null,
                    null);
            
            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按IP和端口获取设备失败: " + e.getMessage(), e);
        }
        
        return entity;
    }
    
    @Override
    public List<PlcDeviceEntity> getActiveDevices() {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDeviceEntity> deviceList = new ArrayList<>();
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    SdgDatabase.COLUMN_IS_ACTIVE + " = 1",
                    null,
                    null,
                    null,
                    SdgDatabase.COLUMN_DEVICE_NAME + " ASC");
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    deviceList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取活动设备失败: " + e.getMessage(), e);
        }
        
        return deviceList;
    }
    
    @Override
    public PlcDeviceEntity getDeviceByIp(String deviceIp) {
        SQLiteDatabase db = database.getReadableDatabase();
        PlcDeviceEntity entity = null;
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    SdgDatabase.COLUMN_DEVICE_IP + " = ?",
                    new String[] { deviceIp },
                    null,
                    null,
                    null);
            
            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "按IP获取设备失败: " + e.getMessage(), e);
        }
        
        return entity;
    }
    
    @Override
    public List<PlcDeviceEntity> getDevicesByTypeId(int deviceTypeId) {
        SQLiteDatabase db = database.getReadableDatabase();
        List<PlcDeviceEntity> deviceList = new ArrayList<>();
        
        try {
            Cursor cursor = db.query(
                    SdgDatabase.TABLE_PLC_DEVICES,
                    null,
                    SdgDatabase.COLUMN_DEVICE_TYPE_ID + " = ?",
                    new String[] { String.valueOf(deviceTypeId) },
                    null,
                    null,
                    SdgDatabase.COLUMN_DEVICE_NAME + " ASC");
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    deviceList.add(cursorToEntity(cursor));
                }
                cursor.close();
            }
            
            Log.d(TAG, "按设备类型ID获取到 " + deviceList.size() + " 个设备");
        } catch (Exception e) {
            Log.e(TAG, "按设备类型ID获取设备失败: " + e.getMessage(), e);
        }
        
        return deviceList;
    }
    
    @Override
    public void deleteAll() {
        SQLiteDatabase db = database.getWritableDatabase();
        try {
            int count = db.delete(SdgDatabase.TABLE_PLC_DEVICES, null, null);
            Log.d(TAG, "已删除所有PLC设备 (" + count + " 个)");
        } catch (Exception e) {
            Log.e(TAG, "删除所有设备失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 将查询结果转换为实体对象
     */
    private PlcDeviceEntity cursorToEntity(Cursor cursor) {
        PlcDeviceEntity entity = new PlcDeviceEntity();
        
        int idIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_ID);
        if (idIndex != -1) {
            entity.setDeviceId(cursor.getInt(idIndex));
        }
        
        int nameIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DEVICE_NAME);
        if (nameIndex != -1) {
            entity.setDeviceName(cursor.getString(nameIndex));
        }
        
        int ipIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DEVICE_IP);
        if (ipIndex != -1) {
            entity.setDeviceIp(cursor.getString(ipIndex));
        }
        
        int portIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DEVICE_PORT);
        if (portIndex != -1) {
            entity.setDevicePort(cursor.getInt(portIndex));
        }
        
        int unitIdIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_UNIT_ID);
        if (unitIdIndex != -1) {
            entity.setUnitId(cursor.getInt(unitIdIndex));
        }
        
        int protocolIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_PROTOCOL);
        if (protocolIndex != -1) {
            entity.setProtocol(cursor.getString(protocolIndex));
        }
        
        int activeIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_IS_ACTIVE);
        if (activeIndex != -1) {
            entity.setActive(cursor.getInt(activeIndex) == 1);
        }
        
        int descIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DESCRIPTION);
        if (descIndex != -1) {
            entity.setDescription(cursor.getString(descIndex));
        }
        
        int timeIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_LAST_CONNECT_TIME);
        if (timeIndex != -1) {
            entity.setLastConnectTime(cursor.getLong(timeIndex));
        }
        
        int deviceTypeIdIndex = cursor.getColumnIndex(SdgDatabase.COLUMN_DEVICE_TYPE_ID);
        if (deviceTypeIdIndex != -1) {
            entity.setDeviceTypeId(cursor.getInt(deviceTypeIdIndex));
        }
        
        return entity;
    }
} 